package com.ja.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ja.domain.Data;
import com.ja.domain.FalseMoney;
import com.ja.domain.Kongzhi;
import com.ja.domain.Order;
import com.ja.domain.PagingData;
import com.ja.domain.Sy;
import com.ja.domain.User;
import com.ja.sevice.FalseMoneyService;
import com.ja.sevice.IDataService;
import com.ja.sevice.IOrderService;
import com.ja.sevice.IUserService;
import com.ja.sevice.KongzhiService;
import com.ja.util.DateUtil;
import com.ja.util.JsonResult;

/**
 * 项目名称：cp   
 * 类名称：OrderController.java   
 * 类描述：   
 * 创建人：   Administrator
 * 创建时间：2019年2月25日 下午2:44:18   
 * @version v1.0.0
 */
@Controller
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private KongzhiService kongzhiService;
	
	@Autowired
	private IDataService dataService;
	
	@Autowired
	private FalseMoneyService falseMoneyService;
	
	/**
	 * 	我的订单页面
	 * @param model 视图对象
	 * @return
	 */
	@RequestMapping("/myOrderPage")
	public ModelAndView myOrderPage(ModelAndView model) {
		model.setViewName("u/myOrders");
		return model;
	}
	
	/**
	  * 方法名：calculateBettingCount 
	  * 描述：     用户投注注数                 
	  * 参数：    @param o
	  * 参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/awards1")
	@ResponseBody
	public JsonResult calculateBettingCount(Order o) {
		return orderService.calculateBettingCount(o);
	}
	
	/**
	 *   方法名：awards   
	 *   描述：     用户下注订单                  TODO 订单下注 
	 *   参数：    @param order 下注信息
	 *   参数：    @param session
	 *   参数：    @return
	 *   参数：    @throws Exception 
	 * @return: JsonResult
	 */
	@RequestMapping("/awards")
	@ResponseBody
	public JsonResult awards(Order order, HttpSession session) {
		User user = (User) session.getAttribute("user");
		return orderService.awards(order, user);
	}
	
	/**
	 * 查询个人订单-全部-待开奖-已开奖-已中奖-已撤单
	 * @param session session 对象
	 * @param paging 分页信息
	 * @param state 订单状态
	 * @param cname 彩种名称
	 * @returne
	 */
	@RequestMapping("/myOrders")  
	@ResponseBody
	public String myOrders(HttpSession session,PagingData paging, Integer state, String cname) {
		User user = (User) session.getAttribute("user");
		Order order  = new Order();
		order.setCname(cname);
		order.setState(state);
		order.setUserid(user.getId());
		paging.setAllCount(orderService.findMyOrdersCounts(order));
		paging.setList(orderService.findMyOrders(paging.getStartIndex(),paging.getLineCount(),user.getId(),state,cname,1));
		return PagingData.pagingData(paging);
	}

	/**
	 * 查询订单相关的彩种
	 * @param session
	 * @return
	 */
	@RequestMapping("/myOrderLotters")
	@ResponseBody
	public JsonResult myOrderLotter(HttpSession session) {
		User user = (User) session.getAttribute("user");
		return new JsonResult("success", orderService.fenleiorder(user.getId()));
	}
	
	/**
	 *   方法名：cancelOrder   
	 *   描述：     彩票订单撤单                  TODO 订单撤单
	 *   参数：    @param id 订单id
	 *   参数：    @param money 撤单金额
	 *   参数：    @param session
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/chedan")
	@ResponseBody
	public JsonResult cancelOrder(int id, double money, HttpSession session){
		User user = (User) session.getAttribute("user");
		return orderService.cancelOrder(user, id);
	}

	/**
	 *   方法名：delOrderById   
	 *   描述：    删除订单                   TODO   
	 *   参数：    @param id 订单id
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/delOrderById")
	@ResponseBody
	public JsonResult delOrderById(int id) {
		return new JsonResult("success", orderService.delOrderById(id)); 
	}

	/**
	 *   方法名：xiazhugs   
	 *   描述：     查询彩种玩法投注球数控制                  TODO   
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/xiazhugs")
	public JsonResult xiazhugs() {
		List<Kongzhi> list = kongzhiService.getAllKongzhi();
		return new JsonResult("success", list);
	}

	/**
	 *   方法名：orderSum   
	 *   描述：     生成彩种当期投注总额                   TODO   
	 *   参数：    @param order 彩种名称
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/orderSum")
	public JsonResult orderSum(String cname,String period) {
		return new JsonResult("success", orderSums(cname,period));
	}
	
	/**
	 * 下注页面请求整合接口  返回下注页面所有数据
	 * @param session  
	 * @param cname  彩种名
	 *
	 * @param type  
	 * @return  返回下注页面全部数据 
	 */
	@ResponseBody
	@RequestMapping("/lotterData")
	public JsonResult lotterData(HttpSession session,String cname,Integer type) {
		String cnames = "";
		switch (cname) {
		case "bjpk10":
		case "2fpk10":
		case "2fft":
		case "xysm":
		case "xyft":
			cnames = "bjpk10";
			break;
		case "cqssc":
		case "2fssc":
		case "tjssc":
		case "xjssc":
			cnames = "cqssc";
			break;
		case "gd11x5":
		case "sd11x5":
		case "sh11x5":
		case "jx11x5":
		case "ah11x5":
			cnames = "gd11x5";
			break;
		case "xg6hc":
		case "5f6hc":
			cnames = "xg6hc";
			break;
		default:
			break;
		}
		//球数
		 List<Kongzhi> kong = kongzhiService.getOneKongzhi(cnames);
		 //获取用户的前
		 User user = (User) session.getAttribute("user");
		 User u = userService.getUserByid(user.getId());
		 session.setAttribute("user", u);
		 //开奖数据
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		 Data data = dataService.findNextNextPeriod(cname,type);
		 if(data != null) {
			 data.setNextStopOrderTimeEpoch(data.getNextStopOrderTimeEpoch().replaceAll("-", "/"));
		 }//data 是当前下注总额    data2 是用户下注记录   暂时注释掉   后面会用  请不要删除
		return new JsonResult(sdf.format(new Date()),/*orderSums(cname,data.getNextperiod())*/"",u.getBalance(),/*orderService.getxzdatas(cname)*/"",kong,data);
	}
	public  String  orderSums(String cname,String period1) {
		Order order = new Order();
		order.setCname(cname);
		order.setPeriod(period1);
		DecimalFormat dec = new DecimalFormat("#0.00");
		double money = orderService.getOrderSum(order);//当期投注总额
		String moneys = dec.format(falseMoneyService.getMoneySum(order) + money); // falseMoneyService.getMoneySum(order)  查询金额
		String period = "";
		if (moneys.equals("0.00")) {
			if("xg6hc".equals(order.getCname())) {
				period = (Long.parseLong(order.getPeriod())+1)+"";
				moneys = dec.format(random1());
			}else {
				period = order.getPeriod();
				moneys = dec.format(random2());
			}
			FalseMoney fm = new FalseMoney();
			fm.setCname(order.getCname());
			fm.setPeriod(period);
			fm.setMoney(Double.parseDouble(moneys));
			fm.setCreateTime(DateUtil.getCurrTime());
			falseMoneyService.addInfo(fm);
		}
		return moneys;
	}
	
	public static double random1() {
		double moneyss = Math.random() * 10000000;
		if (moneyss <= 1600000.00 || moneyss > 2050000.00) {
			moneyss = random1();
		}
		return moneyss;
	}
	
	public static double random2() {
		double moneyss = Math.random() * 100000;
		if (moneyss <= 30000.00 || moneyss > 70000.00) {
			moneyss = random2();
		}
		return moneyss;
	}

	/**
	 *   方法名：zjdata   
	 *   描述：    生成彩种用户中奖数据                   TODO   
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/zjdata")
	public JsonResult zjdata() {
		DecimalFormat df = new DecimalFormat("0.00");
		String[] str = {  "北京PK拾","二分PK拾", "幸运赛马","幸运飞艇", "重庆时时彩", "二分时时彩", "天津时时彩","新疆时时彩", "广东快乐十分", "重庆快乐十分", "安徽11选5",
				"广东11选5", "江西11选5", "山东11选5", "上海11选5", "排列三", "福彩3D", "安徽快3", "广西快3", "江苏快3", "北京快3","三分快3","香港六合彩","五分六合彩",
				"北京28","幸运28","百家乐" };
		List<Sy> list = new ArrayList<Sy>();
		for (int i = 1; i < str.length-1; i++) {
			Sy o1 = new Sy();
			o1.setHuiyuanzh(createUserName(4));
			o1.setCname1(str[createLotteryName(str.length - 1)]);
			o1.setGoalmoney(new Double(df.format((Math.random() * 1000))));
			list.add(o1);
		}
		return new JsonResult("success", list);
	}
	
	/**
	 * 方法名：createUserName 
	 * 描述：    随机生成用户名                   TODO
	 * 参数：    @param length
	 * 参数：    @return 
	 * @return: String
	 */
	public String createUserName(int length) {
		// 定义一个字符串（A-Z，a-z，0-9）即62位；
		String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
		// 由Random生成随机数
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		// 长度为几就循环几次
		for (int i = 0; i < length; ++i) {
			// 产生0-61的数字
			int number = random.nextInt(62);
			// 将产生的数字通过length次承载到sb中
			sb.append(str.charAt(number));
		}
		// 将承载的字符转换成字符串
		return sb.toString();
	}

	/***
	 * 方法名：createLotteryName 
	 * 描述：    随机取彩种名称                    TODO
	 * 参数：    @param num
	 * 参数：    @return 
	 * @return: int
	 */
	public int createLotteryName(int num) {
		while (true) {
			int ii = (int) (1 + Math.random() * num);
			if (num >= ii) {
				return ii;
			}
		}
	}

	/**
	 *   方法名：orderData   
	 *   描述：     查询用户投注订单信息                  TODO   
	 *   参数：    @param cname 彩种名称
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/xzdata")
	public JsonResult orderData(String cname) {
		return new JsonResult("success", orderService.getxzdata(cname));
	}
	
	/**
	 * 查询多个彩种的开奖信息
	 * @param data 彩种名称
	 * @return
	 */
	@RequestMapping("/findDatas")
	@ResponseBody
	public JsonResult findDatas(List<Data> data) {
		return new JsonResult("success", dataService.findDatas(data));
	}

	/**
	 * 修改开奖状态
	 * @param data 彩种信息
	 * @return
	 */
	@RequestMapping("/checkState")
	@ResponseBody
	public JsonResult checkState(Data data) {
		return new JsonResult("success", dataService.changeCheckState(data));
	}
	

}